package com.hf.www.base.model;

import java.util.List;

import com.hf.www.base.common.Pager;
import com.hf.www.core.kit.SqlXmlKit;
import com.hf.www.core.plugin.annotation.Table;
import com.hf.www.tools.EhcacheConstants;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;


@SuppressWarnings("serial")
@Table(tableName="sys_config")
public class SysConfigModel extends Model<SysConfigModel>{

	public static  final SysConfigModel dao = new SysConfigModel();
	
	private static  final Logger LOG = Logger.getLogger(SysConfigModel.class);
	

	/**
	 * 
	 * 数据字典配置的列表数据
	 * 
	 * @param pager
	 * @return
	 */
	public Page<?> page(Pager pager){
		
		Page<?>  page = dao.paginate(pager.getPageNo(), pager.getPageSize(),
				" select u.*  ",
				SqlXmlKit.getSql("SysConfig.pager", pager.getParamsMap()));
		
		return page ;
	}	
	
	
	
	/**
	 * 
	 * 数据字典配置的批量删除
	 * 
	 * @param ids 批量删除的字典配置ID，通过“,” 连接 
	 */
	public void batchDel(String ids){
		
		String arr[] = ids.split("\\,");
		
		for (String id : arr) {
			
			if("".equals(id)){
				continue ;
			}
			
			dao.deleteById(id);
			
		}
		
	}
	
	/**
	 * 根据指定key获取config
	 * 
	 * @param key
	 * @return
	 */
	public List<SysConfigModel> getConfigs(String key) {
		return dao.findByCache(EhcacheConstants.SYS_CONFIG, "KEY_" + key, " SELECT id, `key`, `field`, value,remark,state,sort from sys_config where state=1 and `key`=? order by sort ", key);
	}

	/**
	 * 根据指定key和value获取config
	 * 
	 * @param key
	 * @return
	 */
	public SysConfigModel getConfigs(String key, String val) {
		List<SysConfigModel> configs = getConfigs(key);
		for (SysConfigModel config : configs) {
			if (val != null && val.equals(config.get("value"))) {
				return config;
			}
		}
		return null;
	}

	/**
	 * 获取单个配置对象
	 * 
	 * @param key
	 * @param field
	 * @return
	 */
	public SysConfigModel getConfig(String key, String field) {
		List<SysConfigModel> SysConfigModelList = dao.findByCache(EhcacheConstants.SYS_CONFIG, key + "_" + field, "select `key`,field,value from sys_config where `key`=? and field=? and state=1", key,
				field);
		if (null != SysConfigModelList && SysConfigModelList.size() > 0) {
			return SysConfigModelList.get(0);
		}
		return null;
	}

	
	/**
	 * 
	 * 获取单个数据配置的值
	 * 
	 * @param key
	 * @param field
	 * @return
	 */
	public String getConfigVal(String key, String field) {
		SysConfigModel configModel = getConfig(key, field);
		return (configModel == null) ? "" : configModel.getStr("value");
	}
	
}
